package com.baimsg.reader

import com.baimsg.reader.network.ApiInterface
import com.baimsg.reader.network.HttpUtils
import com.baimsg.reader.thread.TaskThread
import com.baimsg.reader.thread.TaskThreadPoolExecutor
import com.baimsg.reader.util.Log
import com.baimsg.reader.util.extension.appendPath
import com.baimsg.reader.util.extension.toFile
import com.baimsg.reader.util.extension.write
import okhttp3.Headers.Companion.toHeaders
import okhttp3.Request
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * Create by Baimsg on 2022/3/23
 *
 **/
fun main() {
    Log.i("请输入书 ID")
    val sc = Scanner(System.`in`)
    val id = sc.nextLine()
    Log.d("开始加载 -> [id:$id]")
    val bookInfo = ApiInterface.getBookInfo(id)
    if (bookInfo == null) {
        Log.d("加载书籍信息失败！")
        return
    }
    val output = Constant.OUT_PATH.toFile().appendPath(bookInfo.title)
    if (!output.exists()) {
        Log.i("路径：${output.path} [创建${if (output.mkdirs()) "成功" else "失败"}]")
    }
    val sb = StringBuilder()
    sb.append("书名：${bookInfo.title}\n")
    sb.append("字数：${bookInfo.charSize}\n")
    sb.append("作者：${bookInfo.author}\n")
    sb.append("预览图：${bookInfo.coverImg}\n")
    sb.append("简介：${bookInfo.shareDescription}")
    output.appendPath("info.txt").write(sb.toString())
    Log.i("${bookInfo.title} -> info end")
    val request = Request.Builder()
        .get()
        .url(bookInfo.coverImg)
        .build()
    val exe = HttpUtils.client.newCall(request).execute()
    if (exe.isSuccessful) {
        exe.body?.bytes()?.let {
            output.appendPath("cover.png").writeBytes(it)
            Log.i("${bookInfo.title} -> coverImg end")
        }
    } else {
        Log.e("${bookInfo.title} -> coverImg error")
    }
    var leafNodeSum = 0

    bookInfo.portions.forEachIndexed { index, portions ->
        if (portions.leafNode && leafNodeSum < 2) {
            TaskThreadPoolExecutor.threadPoolExecutor.execute(TaskThread(index, output, bookInfo, portions))
        } else {
            leafNodeSum++
        }
    }
    TaskThreadPoolExecutor.threadPoolExecutor.shutdown()
    while (!TaskThreadPoolExecutor.threadPoolExecutor.awaitTermination(1, TimeUnit.SECONDS)) {
        Thread.sleep(800)
    }
    Log.d("${bookInfo.title} -> 缓存结束")
}